/* eslint-disable @iceworks/best-practices/recommend-polyfill */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, column, TitleGrid } from '../stores/definitions';
import TauTable from '@/components/TauTable';

const FromItem = Form.Item;

const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 14,
  },
  style: { marginBottom: 20 },
};

const CompanyRouteForm = ({ priceId, modal, onSubmit, onCancel }) => {
  const { companyRouteStore: store } = useStore();
  const isViewMode = modal[0] === 'view';
  const formProps = isViewMode ? { field: false } : {};
  const [price] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改

  // 重载definitions中的定义，处理一些根据上下文的动态定义
  const overrideModel = {
  };

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      if (priceId) {
        const data = await store.get(priceId);
        const { priceType, startMainArea, startMinorAreas, endMainArea, endMinorAreas } = data;
        await store.companyConsolePrice({
          priceType, startMainArea, startMinorAreas, endMainArea, endMinorAreas,
        });
        editCtx.origin = _.cloneDeep(data);
        _.assign(price, data);
        _.set(price, 'startMinorAreasGroup', { label: price?.fromGroupNames, value: price?.fromGroupNames });
        _.set(price, 'endMinorAreasGroup', { label: price?.toGroupNames, value: price?.toGroupNames });
      } else {
        // 添加操作,设置默认值
        _.set(price, 'type', '2');
        _.set(price, 'priceType', '1');
        _.set(price, 'portTypes', ['0']);
      }
    })();
  }, []);

  if (!price) return <></>;

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(price, name, value);
    // 联动效果可以在这里通过设置price属性实现
    if (name === 'cprice.oneTripPrice.RMB' || name === 'cprice.roundTripPrice.RMB') {
      const prefix = _.trimEnd(name, '.RMB');
      _.set(price, `${prefix}.HKD`, parseFloat(value));
      _.set(price, `${prefix}.MOP`, parseFloat(value));
    }
    if (name === 'startMinorAreasGroup') {
      _.set(price, 'startMinorAreas', value.items.map((itm) => itm.itemId));
    }
    if (name === 'endMinorAreasGroup') {
      _.set(price, 'endMinorAreas', value.items.map((itm) => itm.itemId));
    }

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
    // console.log('form data: ', name, value, toJS(price));
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (value, errors, _field) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: CompanyRouteForm.jsx:95 _ errors:', errors);
      return;
    }
    onSubmit?.(price);
  };

  return (
    <Form
      isPreview={isViewMode}
      {...formProps}
      value={price}
      colon
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`基础信息`} />
      <FieldsGrid
        formData={price}
        overrideModel={overrideModel}
        itemLayout={priceId ? {} : { ...formItemLayout, labelAlign: 'left' }}
        mode={modal[0]}
        columns={priceId ? 4 : 1}
        fields={['startMainArea', 'startMinorAreasGroup', 'endMainArea', 'endMinorAreasGroup']}
      />
      {/* <TitleGrid title={t`线路价格`} /> */}
      <FieldsGrid
        formData={price}
        overrideModel={overrideModel}
        itemLayout={priceId ? {} : { ...formItemLayout, labelAlign: 'left' }}
        mode={modal[0]}
        columns={priceId ? 4 : 1}
        fields={['specificSingleFare.RMB']}
      />
      {priceId && <TitleGrid title={t`平台价格`} />}
      {priceId &&
        <TauTable
          primaryKey="id"
          tableLayout="fixed"
          loading={store.price_loading}
          hidePagination
          dataSource={toJS(store.consolePrice)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('beginAreaName', { width: 128 }),
            column('endAreaName', { width: 128 }),
            column('cprice.oneTripPrice.RMB', { width: 180 }),
          ]}
        />
      }
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          {modal[0] === 'add' && <Form.Submit style={{ marginLeft: 8 }} validate type="primary" onClick={(value, errors, _field) => { price.isReturn = true; handleSubmit(value, errors, _field); }}>{t`保存双向`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(CompanyRouteForm);
